<template>
  <ContentWrap :title="title" v-loading="formLoading">
    <el-form ref="formRef" :model="formData" :rules="rules" label-width="120px">
      <el-row>
        <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
          <el-form-item label="拼团名称" prop="name">
            <el-input v-model="formData.name" class="w-220px!" placeholder="请输入拼团名称" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
          <el-form-item label="活动开始时间" prop="startTime">
            <el-date-picker
              v-model="formData.startTime"
              placeholder="请选择活动开始时间"
              range-separator="-"
              type="date"
              value-format="x"
            />
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
          <el-form-item label="活动结束时间" prop="endTime">
            <el-date-picker
              v-model="formData.endTime"
              placeholder="请选择活动结束时间"
              range-separator="-"
              type="date"
              value-format="x"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
          <el-form-item label="参与人数" prop="userSize">
            <template #label>
              <div>
                参与人数
                <el-tooltip
                  class="box-item"
                  effect="dark"
                  content="参与人数不能少于两人"
                  placement="right"
                >
                  <Icon
                    icon="ep:warning"
                    :size="16"
                    color="var(--el-color-primary)"
                    class="relative top-1px ml-2px"
                  />
                </el-tooltip>
              </div>
            </template>
            <el-input-number v-model="formData.userSize" />
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
          <el-form-item label="弹幕开关" prop="barrageEnable">
            <el-radio-group v-model="formData.barrageEnable">
              <el-radio :value="true">开</el-radio>
              <el-radio :value="false">关</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
          <el-form-item label="单次限购数量" prop="singleLimitCount">
            <el-input-number v-model="formData.singleLimitCount" />
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
          <el-form-item label="总限购数量" prop="totalLimitCount">
            <el-input-number v-model="formData.totalLimitCount" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
          <el-form-item label="虚拟成团" prop="virtualGroup">
            <el-radio-group v-model="formData.virtualGroup">
              <el-radio
                v-for="(dict, index) in getBoolDictOptions(DICT_TYPE.INFRA_BOOLEAN_STRING)"
                :key="index"
                :value="dict.value"
                >{{ dict.label }}</el-radio
              >
            </el-radio-group>
          </el-form-item>
        </el-col>

        <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
          <el-form-item label="团员身份" prop="memberIdentity">
            <el-select
              v-model="formData.memberIdentity"
              class="w-220px!"
              placeholder="请选择团员身份"
            >
              <el-option
                v-for="dict in getIntDictOptions(
                  DICT_TYPE.PROMOTION_COMBINATION_MEMBER_IDENTITY_TYPE
                )"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
          <el-form-item label="背景音乐" prop="videoUrl">
            <el-input v-model="formData.videoUrl" class="w-220px!" placeholder="请输入音乐链接" />
            <el-button @click="openVideo" class="ml-10px" type="primary">选择音乐</el-button>
          </el-form-item>
        </el-col>
        <!-- <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
          <el-form-item label="活动分享图" prop="picUrl">
            <div>
              <UploadImg v-model="formData.picUrl" width="80px" height="80px" />
            </div>
          </el-form-item>
        </el-col> -->
      </el-row>
      <el-row>
        <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
          <el-form-item label="活动分享图" prop="shareImgUrl">
            <div>
              <UploadImg v-model="formData.shareImgUrl" width="80px" height="80px" />
            </div>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
          <el-form-item label="红包图片" prop="redImgUrl">
            <div>
              <UploadImg v-model="formData.redImgUrl" width="80px" height="80px" />
            </div>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
          <el-form-item label="活动公告" prop="notice">
            <el-input
              v-model="formData.notice"
              type="textarea"
              class="w-220px!"
              placeholder="请输入活动公告"
            />
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
          <el-form-item label="活动分享文案" prop="copywriting">
            <div>
              <el-input
                type="textarea"
                v-model="formData.copywriting"
                class="w-220px!"
                placeholder="请输入活动分享文案"
              />
            </div>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
          <el-form-item label="拼团商品" prop="spuId">
            <el-button @click="spuSelectRef.open()">选择商品</el-button>
            <SpuAndSkuList
              ref="spuAndSkuListRef"
              :rule-config="ruleConfig"
              :spu-list="spuList"
              :spu-property-list-p="spuPropertyList"
              class="mt-10px"
            >
              <el-table-column align="center" label="拼团库存" min-width="168">
                <template #default="{ row: sku }">
                  <el-input-number
                    v-model="sku.productConfig.combinationStock"
                    :min="1"
                    :precision="0"
                    :step="1"
                    class="w-100%"
                  />
                </template>
              </el-table-column>
              <el-table-column align="center" label="拼团价格(元)" min-width="168">
                <template #default="{ row: sku }">
                  <el-input-number
                    v-model="sku.productConfig.combinationPrice"
                    :min="0"
                    :precision="2"
                    :step="0.1"
                    class="w-100%"
                  />
                </template>
              </el-table-column>
            </SpuAndSkuList>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
          <el-form-item label="活动详情" prop="content">
            <Editor v-model:modelValue="formData.content" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <el-form>
      <el-form-item style="float: right">
        <el-button :loading="formLoading" type="primary" @click="submitForm"> 保存 </el-button>
        <el-button @click="close">返回</el-button>
      </el-form-item>
    </el-form>
    <SpuSelect ref="spuSelectRef" :isSelectSku="true" @confirm="selectSpu" />
    <upload-attachment type="2" ref="videoRef" @confirm="videoSelect" />
  </ContentWrap>
</template>
<script lang="ts" setup>
import { cloneDeep } from 'lodash-es'
import { useTagsViewStore } from '@/store/modules/tagsView'
import * as CombinationActivityApi from '@/api/mall/promotion/combination/combinationActivity'
import { CombinationProductVO } from '@/api/mall/promotion/combination/combinationActivity'
import { SpuAndSkuList, SpuProperty, SpuSelect } from '@/views/mall/promotion/components'
import { getPropertyList, RuleConfig } from '@/views/mall/product/spu/components'
import * as ProductSpuApi from '@/api/mall/product/spu'
import { convertToInteger, formatToFraction } from '@/utils'
import { DICT_TYPE, getBoolDictOptions, getIntDictOptions } from '@/utils/dict'
import { Editor } from '@/components/Editor'
import UploadAttachment from '@/views/app/components/upload-attachment/index.vue'

defineOptions({ name: 'ActivityAdd' })
const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formRef = ref() // 表单 Ref

const title = ref('超级拼团活动创建')
const { push, currentRoute } = useRouter() // 路由
const { params } = useRoute() // 查询参数
const { delView } = useTagsViewStore() // 视图操作
const formData = ref<CombinationActivityApi.CombinationActivityVO>({
  name: undefined,
  startTime: undefined,
  endTime: undefined,
  userSize: 2,
  barrageEnable: true,
  virtualGroup: false,
  memberIdentity: 1,
  totalLimitCount: 0,
  singleLimitCount: 0,
  type: 1,
  content: '',
  videoUrl: '',
  products: [],
  limitDuration: 0,
  copywriting: '',
  notice: '',
  redImgUrl: '',
  shareImgUrl: ''
})
const rules = reactive({
  name: [required],
  totalLimitCount: [required],
  singleLimitCount: [required],
  startTime: [required],
  endTime: [required],
  userSize: [required],
  limitDuration: [required],
  virtualGroup: [required],
  // headIdentity: [required],
  memberIdentity: [required]
})

// ================= 相关 =================

const spuSelectRef = ref() // 商品和属性选择 Ref
const spuAndSkuListRef = ref() // sku 秒杀配置组件Ref
const spuList = ref<CombinationActivityApi.SpuExtension[]>([]) // 选择的 spu
const spuPropertyList = ref<SpuProperty<CombinationActivityApi.SpuExtension>[]>([])
const ruleConfig: RuleConfig[] = [
  {
    name: 'productConfig.combinationPrice',
    rule: (arg) => arg >= 0.01,
    message: '商品拼团价格不能小于0.01 ！！！'
  },
  {
    name: 'productConfig.combinationStock',
    rule: (arg) => arg >= 1,
    message: '商品拼团库存不能小于1 ！！！'
  }
]
const selectSpu = (spuId: number, skuIds: number[]) => {
  formData.value.spuId = spuId
  getSpuDetails(spuId, skuIds)
}
/**
 * 获取 SPU 详情
 */
const getSpuDetails = async (
  spuId: number,
  skuIds: number[] | undefined,
  products?: CombinationProductVO[]
) => {
  const spuProperties: SpuProperty<CombinationActivityApi.SpuExtension>[] = []
  const res = (await ProductSpuApi.getSpuDetailList([
    spuId
  ])) as CombinationActivityApi.SpuExtension[]
  if (res.length == 0) {
    return
  }
  spuList.value = []
  // 因为只能选择一个
  const spu = res[0]
  const selectSkus =
    typeof skuIds === 'undefined'
      ? spu?.skus
      : spu?.skus?.filter((sku) => skuIds.includes(sku.skuId!))
  selectSkus?.forEach((sku) => {
    let config: CombinationProductVO = {
      spuId: spu.spuId!,
      skuId: sku.skuId!,
      combinationPrice: 0,
      combinationStock: 1
    }
    if (typeof products !== 'undefined') {
      const product = products.find((item) => item.skuId === sku.skuId)
      if (product) {
        product.combinationPrice = formatToFraction(product.combinationPrice)
      }
      config = product || config
    }
    sku.productConfig = config
    sku.price = formatToFraction(sku.price)
    sku.marketPrice = formatToFraction(sku.marketPrice)
    sku.costPrice = formatToFraction(sku.costPrice)
    sku.firstBrokeragePrice = formatToFraction(sku.firstBrokeragePrice)
    sku.secondBrokeragePrice = formatToFraction(sku.secondBrokeragePrice)
  })
  spu.skus = selectSkus as CombinationActivityApi.SkuExtension[]
  spuProperties.push({
    spuId: spu.spuId!,
    spuDetail: spu,
    propertyList: getPropertyList(spu)
  })
  spuList.value.push(spu)
  spuPropertyList.value = spuProperties
}

// ================= end =================
/** 获得详情 */
const getDetail = async () => {
  const id = params.id as unknown as number
  formType.value = 'create'
  await resetForm()

  if (id) {
    formLoading.value = true
    formType.value = 'update'
    title.value = '超级拼团活动编辑'
    try {
      const data = (await CombinationActivityApi.getCombinationActivity(
        id
      )) as CombinationActivityApi.CombinationActivityVO
      await getSpuDetails(
        data.spuId!,
        data.products?.map((sku) => sku.skuId),
        data.products
      )

      formData.value = data
    } finally {
      formLoading.value = false
    }
  }
}
/** 提交按钮 */
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  const id = params.id as unknown as number
  // 提交请求
  formLoading.value = true
  try {
    // 获得拼团商品配置
    const products = cloneDeep(spuAndSkuListRef.value.getSkuConfigs('productConfig'))
    products.forEach((item: CombinationActivityApi.CombinationProductVO) => {
      item.combinationPrice = convertToInteger(item.combinationPrice)
    })
    const data = cloneDeep(formData.value) as CombinationActivityApi.CombinationActivityVO
    data.products = products
    data.type = 1
    if (!id) {
      await CombinationActivityApi.createCombinationActivity(data)

      message.success(t('common.createSuccess'))
    } else {
      await CombinationActivityApi.updateCombinationActivity(data)

      message.success(t('common.updateSuccess'))
    }
    close()
  } finally {
    formLoading.value = false
  }
}
/** 重置表单 */
const resetForm = async () => {
  spuList.value = []
  spuPropertyList.value = []
  await nextTick()
  formData.value = {
    name: undefined,
    startTime: undefined,
    endTime: undefined,
    userSize: 2,
    barrageEnable: true,
    virtualGroup: false,
    memberIdentity: 1,
    totalLimitCount: 0,
    singleLimitCount: 0,
    type: 1,
    content: '',
    videoUrl: '',
    products: [],
    copywriting: '',
    notice: '',
    redImgUrl: '',
    shareImgUrl: '',
    limitDuration: 0
  }
}

/** 关闭按钮 */
const close = () => {
  delView(unref(currentRoute))
  push({ name: 'PromotionSuperCombinationActivity' })
}
const videoRef = ref()
const openVideo = () => {
  videoRef.value.showDialog = true
}
const videoSelect = (data: Record<string, any>) => {
  formData.value.videoUrl = data.url
}
/** 初始化 */
onMounted(async () => {
  await getDetail()
})
</script>
